//
//  DAUserListViewController.m
//  DAKnowledge
//
//  Created by DreamArts on 16/6/1.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DAUserListViewController.h"
#import "DAUserModel.h"
#import "DAUserListTableViewCell.h"
#import "DAFileListTableViewCell.h"
#import "DAOtherPersonalViewController.h"
#import "DAFileListViewController.h"
#import "DAOtherPersonalViewController.h"
#import "DAUserFileModel.h"
#import "DAUserFileModel.h"
#import "DAWebFileViewController.h"
#import "DAAllFileModel.h"
#import "DANetWorkReachabilityStatus.h"

@interface DAUserListViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate, UISearchBarDelegate, UISearchControllerDelegate, userDetail>{
    UIView *statusCover;
}
//@property (nonatomic, strong) UISearchController *searchController;
//@property (nonatomic, strong) UITableView *tableView;
// 所有key的数组
@property (nonatomic, strong) NSMutableArray *keys;
// 搜索结果的数组
@property (nonatomic, strong) NSMutableArray *searchResults;
// 索引数组
@property (nonatomic, strong) NSMutableArray *indexArray;
// 数组里是model
@property (nonatomic, strong) NSMutableArray *dataArray;
//  存储所有文件
@property (nonatomic, strong) NSMutableArray *fileDataArray;
// 数组里A-Z的数组
@property (nonatomic, strong) NSMutableArray *charactorArray;
//
@property (nonatomic, strong) NSMutableDictionary *userDic;

@property (weak, nonatomic) IBOutlet UIView *searchBarBackView;

@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;

@property (strong, nonatomic) IBOutlet UISearchDisplayController *searchDisplayController;

@property (weak, nonatomic) IBOutlet UITableView *tableVIew;
@property (nonatomic, strong) NSMutableArray *collectFiles;

@property (nonatomic, strong) NSArray *allFileArray;
//@property (nonatomic, strong) UISearchDisplayController *searchController;
//@property (nonatomic, strong) UISearchBar *searchBar;
@end

@implementation DAUserListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //NSString *userList = NSLocalizedString(@"userList", nil);
    //self.title = userList;
    [self ConfigurationNavigation];
    [self prepareData];
    [self prepareFileData];
    [self readLocalData];
    [self creatTableView];
    [self searchSetting];
    
    [self.tableVIew.mj_header beginRefreshing];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.translucent = YES;
}
- (void)ConfigurationNavigation{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"Resource" style:UIBarButtonItemStylePlain target:self action:nil];
    self.navigationItem.leftBarButtonItem.enabled = NO;
    [self.navigationItem.leftBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15],NSFontAttributeName,[UIColor whiteColor],NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
}
- (void)creatTableView{
    self.tableVIew.dataSource = self;
    self.tableVIew.delegate = self;
    self.tableVIew.tableFooterView = [UIView new];
    self.tableVIew.rowHeight = 60;
    self.tableVIew.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    self.searchDisplayController.searchResultsTableView.frame = CGRectMake(0, 0, self.view.frame.size.width, 350);
    self.searchDisplayController.searchResultsTableView.rowHeight = 60;
    self.searchDisplayController.searchResultsTableView.tableFooterView = [UIView new];
    self.searchDisplayController.searchResultsTableView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    self.tableVIew.tableFooterView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    self.tableVIew.tableHeaderView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    self.tableVIew.sectionIndexBackgroundColor = [UIColor clearColor];
    self.tableVIew.sectionIndexColor = [UIColor supportGreenColor];
     // self.tableVIew.editing = YES;
   // self.searchDisplayController.searchResultsTableView.editing = YES;
    //
    MJRefreshGifHeader *header =[MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    NSMutableArray *refreshImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"page%ld@3x", (unsigned long)i]];
        [refreshImages addObject:image];
    }
    NSMutableArray *normalImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"stay%ld@3x", (unsigned long)i]];
        [normalImages addObject:image];
    }
    UIImage *image = [UIImage imageNamed:@"stay21@3x"];
    [normalImages insertObject:image atIndex:0];
    
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStateRefreshing];
    [header setImages:normalImages forState:MJRefreshStateIdle];
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStatePulling];
    
    header.lastUpdatedTimeLabel.hidden= YES;//如果不隐藏这个会默认 图片在最左边不是在中间
    header.stateLabel.hidden = YES;
    self.tableVIew.mj_header = header;

}

//读取本地数据
- (void) readLocalData{
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:@"UserInfo"];
    NSMutableArray *arr = [self getLocalDataWithPath:path];
    self.dataArray = arr;
    //NSLog(@"dataArray数据 %@",self.dataArray);
}

- (void)refreshData{
    [self prepareData];
    //索引数组
    [self readLocalData];
    [self arraySort];
    [self.tableVIew reloadData];
    [self.tableVIew.mj_header endRefreshing];
  
}
//#pragma mark -创建tableView
//- (void)creatTableView{
//    self.view.backgroundColor = [UIColor colorWithHexString:backGroundColor];
//    self.navigationController.navigationBar.translucent = NO;
//    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 45, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
//    self.tableView.dataSource = self;
//    self.tableView.delegate = self;
//    [self.view addSubview:self.tableView];
//    self.tableView.tableFooterView = [UIView new];
//    self.tableView.rowHeight = 60;
//    self.tableView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
//    self.tableView.sectionIndexColor = [UIColor supportGreenColor];
//   // self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
//}
//#pragma mark - searchController创建
//- (void)setUpSearchController{
//    self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
//    self.searchController.searchBar.frame = CGRectMake(0, 0, 0, 40);
//    [self.view addSubview:self.searchController.searchBar];
//    self.searchController.dimsBackgroundDuringPresentation = NO;
//   // self.tableView.tableHeaderView = self.searchController.searchBar;
//    [self.searchController.searchBar sizeToFit];
//    self.searchController.searchBar.backgroundImage = [self imageWithColor:[UIColor clearColor] size:self.searchController.searchBar.bounds.size];
//    self.searchController.searchResultsUpdater = self;
//    self.searchController.searchBar.delegate = self;
//    [self.searchController.searchBar setTintColor:[UIColor whiteColor]];
//    [[[[self.searchController.searchBar.subviews objectAtIndex:0] subviews] objectAtIndex:0] removeFromSuperview];
//    
//}

- (void)searchSetting{
    self.searchBar.backgroundImage = [self imageWithColor:[UIColor clearColor] size:self.searchBar.bounds.size];
    NSString *userSearchPlaceHolder = NSLocalizedString(@"Input keywords to search file", nil);
    self.searchBar.placeholder = userSearchPlaceHolder;
    self.searchBar.delegate = self;
    // self.tableView.tableHeaderView = self.search;
    self.searchDisplayController.delegate = self;
    UITextField *text = [self.searchBar valueForKey:@"_searchField"];
    [text setValue:[UIFont systemFontOfSize:12] forKeyPath:@"_placeholderLabel.font"];
    self.searchBarBackView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    [self.searchBar setTintColor:[UIColor whiteColor]];
    [[[[self.searchDisplayController.searchBar.subviews objectAtIndex:0] subviews] objectAtIndex:0] removeFromSuperview];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    [self.searchDisplayController.searchBar setBackgroundColor:[UIColor supportGreenColor]];
    statusCover = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 20)];
    statusCover.backgroundColor = [UIColor supportGreenColor];
    [self.view addSubview:statusCover];
    [self.searchBar setTintColor:[UIColor whiteColor]];
    [self.searchDisplayController.searchResultsTableView reloadData];
    
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [self.searchDisplayController.searchBar setBackgroundColor:[UIColor colorWithHexString:backGroundColor]];
    [statusCover removeFromSuperview];
    [self.searchBar setTintColor:[UIColor darkGrayColor]];
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    //[self refreshData];
    [self prepareFileData];
    [self.searchDisplayController.searchResultsTableView reloadData];
}
#pragma mark - 准备数据 (读取用户)
- (void)prepareData{
    NSString *url = DAUserListURL;
   // NSString *isloading = NSLocalizedString(@"isLoading", nil);
    //[SVProgressHUD showWithStatus:isloading];
    [DADataHandel postURL:url parame:nil cookie:nil result:^(id result) {
        if ([result[@"result"] isKindOfClass:[NSArray class]] && [result[@"result"] count] > 0) {
            //数据保存到本地
            [self archiveToLocalWithData:result];
//            DAUserModel *userModel = [[DAUserModel alloc]init];
//            self.dataArray = [NSMutableArray array];
//            self.dataArray = [userModel returnModelInArrayWithArray:result[@"result"]];
//            [self arraySort];
//            [self.tableVIew reloadData];
//            [self finishLoadDataMBProgress];
//            [self.tableVIew.mj_header endRefreshing];
            [self readLocalData];
            [self arraySort];
            [self.tableVIew reloadData];
            
        }else{
            NSLog(@"请求数据失败");
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
                [self.tableVIew.mj_header endRefreshing];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
                [self.tableVIew.mj_header endRefreshing];
                
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
                [self.tableVIew.mj_header endRefreshing];
            }
            else{
                [SVProgressHUD showErrorWithStatus:self.requestFailed];
                [self.tableVIew.mj_footer endRefreshing];
            }
            
            [self readLocalData];
            [self arraySort];
            [self.tableVIew reloadData];

        }
    }];
}

#pragma mark - 准备数据 (读取所有文件)
- (void)prepareFileData{
    NSString *url = DAFileUrl;
    [self dataHandelWithUrl:url parame:nil];
}
- (void)dataHandelWithUrl:(NSString *)url parame:(NSDictionary *)dic{
    __weak typeof(self) weakSelf = self;
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        if ([result[@"result"] isKindOfClass:[NSArray class]]){
            [weakSelf dataTransFormModel:result[@"result"]];
        }else{
            NSLog(@"请求数据失败");
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                //[SVProgressHUD showErrorWithStatus:self.requestTimeOut];
                //[weakSelf.tableVIew.mj_header endRefreshing];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                //[SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
               // [weakSelf.tableVIew.mj_header endRefreshing];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                //[SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
               // [weakSelf.tableVIew.mj_header endRefreshing];
            }
            else{
               // [SVProgressHUD showErrorWithStatus:self.requestFailed];
               // [weakSelf.tableVIew.mj_footer endRefreshing];
            }
        }
    }];
}
- (void)dataTransFormModel:(NSArray *)resultArray{
//    DAUserFileModel *userFileModel = [[DAUserFileModel alloc]init];
//    NSArray *array = [userFileModel returnModelInArrayWithDic:resultArray];
//        
//    _fileDataArray = [NSMutableArray array];
//    [_fileDataArray addObjectsFromArray:array];
//    NSLog(@"fileDataArray");
    
    self.allFileArray = [DAAllFileModel returnModelWithArray:resultArray];
   // NSLog(@"%@", self.allFileArray);
    
}



#pragma mark -
- (void)arraySort{
    self.keys = [NSMutableArray array];
    self.indexArray = [NSMutableArray array];
    self.userDic = [NSMutableDictionary dictionary];
    self.charactorArray = [NSMutableArray array];
    for (char a = 'A'; a <= 'Z'; a++) {
        [self.charactorArray addObject:[NSString stringWithFormat:@"%c", a]];
    }
    for (DAUserModel *userModel in self.dataArray) {
        NSString *key = [self firstCharactor:userModel.userName];
        [self.keys addObject:key];
    }
    for (NSString *key in self.keys) {
        NSMutableArray *arr = [NSMutableArray array];
        [self.userDic setObject:arr forKey:key];
    }
    for (DAUserModel *userModel in self.dataArray) {
        NSString *key = [self firstCharactor:userModel.userName];
        [self.userDic[key] addObject:userModel];
    }
    self.indexArray = [[self.userDic.allKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]mutableCopy];
    if ([self.indexArray containsObject:@"#"]) {
        [self.indexArray removeObject:@"#"];
        [self.indexArray addObject:@"#"];
    }
    
    
}
#pragma mark - tabelView dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.searchDisplayController.active) {
        return 1;
    }else{
        return self.indexArray.count;
    }
}
// 索引内容
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
//    if (self.searchDisplayController.active) {
//        return nil;
//    }else{
//        return self.indexArray;
//    }
//
    if (tableView == self.tableVIew) {
        return self.indexArray;
    }else{
        return nil;
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
//    if (self.searchDisplayController.active) {
//        return nil;
//    }else {
//        return [self.indexArray objectAtIndex:section];
//    }
    
    if (tableView == self.tableVIew) {
        return [self.indexArray objectAtIndex:section];
    }else{
        return nil;
    }
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSString *key = self.indexArray[section];
    NSArray *arr = [self.userDic objectForKey:key];
  //  return (!self.searchDisplayController.active)? arr.count : self.searchResults.count;
    
    if (tableView == self.tableVIew) {
        return arr.count;
    }else{
        return  self.searchResults.count;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.tableVIew) {
        DAUserListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"userList"];
        if (cell == nil) {
            cell = [[DAUserListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"userList"];
        }
        NSString *key = self.indexArray[indexPath.section];
        NSArray *arr = [self.userDic objectForKey:key];
        cell.userModel = arr[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor whiteColor];
        cell.delegate = self;
        return cell;

    }else{
        DAFileListTableViewCell *cell = [self.tableVIew dequeueReusableCellWithIdentifier:@"file_search"];
        if (cell == nil) {
            cell = [[DAFileListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"file_search"];
        }
        cell.userFileModel = self.searchResults[indexPath.row];
        DAUserFileModel *model = self.searchResults[indexPath.row];
        //cell.userFileModel = self.searchResults[indexPath.row];
        
        //判断是否已经下载
        NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [path objectAtIndex:0];
        BOOL isExist = [self isFileExist:[NSString stringWithFormat:@"%@.%@",model.filefolderName,model.fileExtend] inPath:documentsDirectory];
        if (isExist) {
            model.isDownloadingSuccessful = YES;
        }
        cell.userFileModel = model;
        //cell.backgroundColor = [UIColor redColor];
    
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    
//    NSString *key = self.indexArray[indexPath.section];
//    NSArray *arr = [self.userDic objectForKey:key];
//
//    DAOtherPersonalViewController *otherPersonal = [self.storyboard instantiateViewControllerWithIdentifier:@"OTHERPERSONAL"];
//    otherPersonal.hidesBottomBarWhenPushed = YES;
//    if (tableView == self.tableVIew) {
//        otherPersonal.otherUserID = [arr[indexPath.row] userID];
//    }else{
//        otherPersonal.otherUserID = [self.searchResults[indexPath.row] userID];
//    }
//    [self.navigationController pushViewController:otherPersonal animated:YES];
    if (tableView == self.tableVIew) {
        NSString *key = self.indexArray[indexPath.section];
        NSArray *arr = [self.userDic objectForKey:key];
        DAFileListViewController *fileList = [self.storyboard instantiateViewControllerWithIdentifier:@"FILELIST"];
        fileList.hidesBottomBarWhenPushed = YES;
        fileList.ID = [arr[indexPath.row] userID];
        fileList.name = [arr[indexPath.row] userName];
        fileList.fileNum = [arr[indexPath.row] fileNum];
        [self.navigationController pushViewController:fileList animated:YES];
        
    }else{   //搜索结果的点击方法
        
        [self.searchDisplayController.searchResultsTableView deselectRowAtIndexPath:indexPath animated:YES];
         DAUserFileModel *model = [self.searchResults objectAtIndex:indexPath.row];
        DAFileListTableViewCell *cell = [[DAFileListTableViewCell alloc]init];
        cell = [self.searchDisplayController.searchResultsTableView cellForRowAtIndexPath:indexPath];
        
        //文件保存路径
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [NSString stringWithFormat:@"%@/%@.%@", documentsDirectory, model.filefolderName,model.fileExtend];
        NSLog(@"文件保存路径 %@",documentsDirectory);
        
        //文件下载路径
//        NSString *str = model.fileUrl;
//        NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)str, NULL, NULL,  kCFStringEncodingUTF8 ));
//        NSURL *url = [NSURL URLWithString:encodedString];
        
        //判断文件在本地是否存在
        if (model.isDownloading == YES) {
            NSLog(@"正在下载");
        }else{
        BOOL isExist = [self isFileExist:[NSString stringWithFormat:@"%@.%@",model.filefolderName,model.fileExtend] inPath:documentsDirectory];
        if (isExist) {
            NSLog(@"文件存在可以直接打开");
            DAWebFileViewController *webFile = [[DAWebFileViewController alloc]init];
            webFile.fileUrl = filePath;
            webFile.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:webFile animated:YES];
        }else{
            //下载文件
            //判断网络连接
            [DANetWorkReachabilityStatus isNetWorkConnectWithBlock:^(BOOL isConnect){
                if (isConnect) {
                    NSLog(@"下载文件");
                    cell.progress.hidden = NO;
                    model.isDownloading = YES;
                    [NSThread detachNewThreadSelector:@selector(downloadSearchFile:) toTarget:self withObject:indexPath];
                }else{
                    NSString *str = NSLocalizedString(@"NoNetWorkCouldNotDownload", nil);
                    [SVProgressHUD showErrorWithStatus:str];
                }
            }];
//            if ([DANetWorkReachabilityStatus isNetWorkConnect]) {
//                NSLog(@"下载文件");
//                cell.progress.hidden = NO;
//                model.isDownloading = YES;
//                [NSThread detachNewThreadSelector:@selector(downloadSearchFile:) toTarget:self withObject:indexPath];
//            }else{
//                NSString *str = NSLocalizedString(@"NoNetWorkCouldNotDownload", nil);
//                [SVProgressHUD showErrorWithStatus:str];
//            }
            }
        }
    }
}

//Cell 左划响应事件
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView != self.tableVIew) {
        return  UITableViewCellEditingStyleDelete;
    }else{
        return UITableViewCellEditingStyleNone;
    }
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    DAUserFileModel *model = [self.searchResults objectAtIndex:indexPath.row];
    BOOL flag = false;
    flag = [[DACollectionFiles shareDACollectionFiles] isContainCollectionsWith:model.fileID];
    
    
    if (!flag) {
        //收藏按钮
        UITableViewRowAction *collectRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"收藏" handler:^(UITableViewRowAction *_Nonnull action, NSIndexPath * _Nonnull indexPath){
            NSLog(@"收藏");
            NSDictionary *dic;
            NSString *url = DACollectionFile;
            dic = @{@"collectUserID":self.userID , @"collectFolderName":model.filefolderName};
            
            [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
                if (result) {
                    NSLog(@"结果 %@",result);
                    //NSLog(@"收藏成功!");
                    [SVProgressHUD showSuccessWithStatus:@"收藏成功"];
                    //[self.collectFiles addObject:model];
                    [[DACollectionFiles shareDACollectionFiles] updateWithUserID:self.userID Block:^(NSMutableArray *array) {
                        self.collectFiles = array;
                    }];
                    if (tableView == self.tableVIew) {
                        [self.tableVIew reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }else{
                        [self.searchDisplayController.searchResultsTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }
                }else{
                    NSLog(@"收藏失败!");
                    [SVProgressHUD showErrorWithStatus:@"收藏失败"];
                }
            }];
            //NSLog(@"用户 : %@  文件 : %@",self.userID,model.filefolderName);
        }];
        collectRowAction.backgroundColor = [UIColor orangeColor];
        //  [self prepareCollectFiles];
        return  @[collectRowAction];
    }else{
        //取消收藏按钮
        UITableViewRowAction *collectRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"取消收藏" handler:^(UITableViewRowAction *_Nonnull action, NSIndexPath * _Nonnull indexPath){
            NSLog(@"取消收藏");
            NSDictionary *dic;
            NSString *url = DACancelCollectionFile;
            dic = @{@"collectUserID":self.userID , @"collectFolderName":model.filefolderName};
            
            [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
                NSLog(@"结果 %@",result);
                if (result) {
                    //NSLog(@"收藏成功!");
                    [SVProgressHUD showSuccessWithStatus:@"取消收藏成功"];
                    //[self.collectFiles removeObject:trans];
                    [[DACollectionFiles shareDACollectionFiles]updateWithUserID:self.userID Block:^(NSMutableArray *array) {
                        self.collectFiles = array ;
                    }];
                    if (tableView == self.tableVIew) {
                        [self.tableVIew reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }else{
                        [self.searchDisplayController.searchResultsTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }
                }else{
                    NSLog(@"取消收藏失败!");
                    [SVProgressHUD showErrorWithStatus:@"取消收藏失败"];
                }
            }];
        }];
        collectRowAction.backgroundColor = [UIColor orangeColor];
        // [self prepareCollectFiles];
        return @[collectRowAction];
    }
    //return tabItems;

    
}


#pragma mark - 判断沙盒里是否有这个文件
-(BOOL)isFileExist:(NSString *)fileName inPath:(NSString *)path{
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    //  NSLog(@"该文件：%@",result?@"有！！":@"不存在");
    return result;
}
#pragma marks - 下载搜索结果文件
- (void)downloadSearchFile:(NSIndexPath *)indexPath{
    DAFileListTableViewCell *cell = [[DAFileListTableViewCell alloc]init];
    cell = [self.searchDisplayController.searchResultsTableView cellForRowAtIndexPath:indexPath];
    //    NSString *key = self.indexArray[indexPath.section];
    //    NSArray *arr = [self.userDic objectForKey:key];
    DAUserFileModel *model = [self.searchResults objectAtIndex:indexPath.row];
    //  NSLog(@"MODEL %@",model.filefolderName);
    //文件保存路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"文件保存路径 %@",documentsDirectory);
    
    //文件下载路径
    NSString *str = model.fileUrl;
    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)str, NULL, NULL,  kCFStringEncodingUTF8 ));
    NSURL *url = [NSURL URLWithString:encodedString];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString  *fullPath = [NSString stringWithFormat:@"%@/%@.%@", documentsDirectory, model.filefolderName,model.fileExtend];
    // NSURL *url = [NSURL URLWithString:@"http://www.abc.com/test.mp4"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *task =
    [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        CGFloat count = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
        dispatch_async(dispatch_get_main_queue(), ^{
            [cell.progress setProgress:count animated:YES];
        });
        //  NSLog(@"下载进度 %f",count);
        //    if (self.isFinish == NO) {
        //            [SVProgressHUD  showProgress:count];
        //        }
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        cell.progress.hidden = YES;
        cell.downLoadCompleteImage.image = [UIImage imageNamed:@"complete@3x"];
        model.isDownloading = NO;
        //[SVProgressHUD dismiss];
        // [self creatPreview];
    }];
    [task resume];
    
}

#pragma mark - 下载文件
- (void)downLoadFile:(NSString *)fileName saveInPath:(NSString *)path fromURL:(NSURL *)url{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString  *fullPath = [NSString stringWithFormat:@"%@/%@", path, fileName];
    // NSURL *url = [NSURL URLWithString:@"http://www.abc.com/test.mp4"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *task =
    //    [manager downloadTaskWithRequest:request
    //                            progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    //                                return [NSURL fileURLWithPath:fullPath];
    //                            }
    //                   completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    //
    //                   }];
    
    [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        CGFloat count = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
        //        if (self.isFinish == NO) {
        //            [SVProgressHUD  showProgress:count];
        //        }
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        // [self creatPreview];
    }];
    [task resume];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20)];
    view.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 10, 100, 10)];
    label.text = [self.indexArray objectAtIndex:section];
    label.font = [UIFont boldSystemFontOfSize:14];
    label.textColor = [UIColor darkGrayColor];
    [view addSubview:label];
    return view;
}

- (NSString *)firstCharactor:(NSString *)string{
    NSMutableString *str = [NSMutableString stringWithString:string];
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, YES);
    NSString *largeStr = [str capitalizedString];
    NSString *firstStr;
    if (string.length != 0) {
        firstStr = [largeStr substringToIndex:1];
    }
    BOOL isContain = [self.charactorArray containsObject:firstStr];
    if (isContain == NO || [firstStr isEqualToString:@""]) {
        firstStr = @"#";
    }
    return firstStr;
}
//- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
//    [self.searchResults removeAllObjects];
////    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"self contains[cd] %@", self.searchController.searchBar.text];
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userName contains[cd] %@", self.searchBar.text];
//    self.searchResults = [[self.dataArray filteredArrayUsingPredicate:predicate]mutableCopy];
//    NSLog(@"%@", self.searchResults);
//
//    [self.tableVIew reloadData];
//}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
    
    [self.searchResults removeAllObjects];
    //    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"self contains[cd] %@", self.searchController.searchBar.text];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"fileName contains[cd] %@", self.searchBar.text];
    self.searchResults = [[self.allFileArray filteredArrayUsingPredicate:predicate]mutableCopy];
   // NSLog(@"%@", self.searchResults);
    
  //  [self.tableVIew reloadData];
    [self.searchDisplayController.searchResultsTableView reloadData];

    return YES;
}

#pragma mark - 跳转到个人页面协议方法
- (void)userDetailWithUserId:(NSString *)userId{
    DAOtherPersonalViewController *otherPersonal = [self.storyboard instantiateViewControllerWithIdentifier:@"OTHERPERSONAL"];
    otherPersonal.hidesBottomBarWhenPushed = YES;
    otherPersonal.otherUserID = userId;
    [self.navigationController pushViewController:otherPersonal animated:YES];
}
#pragma mark - searchBar背景颜色
- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


#pragma mark - 解决UISearchDisplayController searchResultsTableView 的ContentSize bug
- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView{
    CGRect testFrame = CGRectMake(0, 0, self.searchBar.frame.size.width, self.view.bounds.size.height-113);
    
    self.searchDisplayController.searchResultsTableView.frame = testFrame;
    [tableView setContentInset:UIEdgeInsetsZero];
    [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
}

- (void)dealloc{
    self.tableVIew.delegate = nil;
    self.searchBar.delegate = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 数据保存到本地
- (void) archiveToLocalWithData:(NSDictionary *)data{
    //创建路径
   NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:@"UserInfo"];
    BOOL isSuccess = [data writeToFile:path atomically:YES];
    NSLog(@"用户数据 保存 :%@",path);
    if (isSuccess) {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setBool:YES forKey:@"isLocalFileData"];
    }
}

#pragma mark - 从本地取出数据
- (NSMutableArray *)getLocalDataWithPath:(NSString *)path{
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
    DAUserModel *userModel = [[DAUserModel alloc]init];
    NSMutableArray *array = [userModel returnModelInArrayWithArray:dic[@"result"]];
    return array;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
